# -*- coding: utf-8 -*-
# file: upload_to_cloud.py
# author: JinTian
# time: 18/03/2017 2:48 PM
# Copyright 2017 JinTian. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------
from qiniu import Auth, put_file, etag, urlsafe_base64_encode
import qiniu.config
from random import sample


qiniu_config = {
    'access_key': '33HnfbHNaNgwZbIsuEO3gkXmhEZtUzDhFfHaK2YK',
    'secret_key': '7SMsLJyeM_SnyIAkEypTCwPuV_W-L_OJtFt7RFfb',
    'bucket_name': 'oumenglite',
    'bucket_dominate': 'ommwypwud.bkt.clouddn.com'
}


def upload_to_qiniu(local_file):
    save_name = ''.join(sample('AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789', 16))
    save_name = str(save_name + '.jpg')

    try:
        q = Auth(access_key=qiniu_config['access_key'], secret_key=qiniu_config['secret_key'])
        token = q.upload_token(qiniu_config['bucket_name'], key=save_name, expires=3600)

        ret, info = put_file(token, key=save_name, file_path=local_file)
        picture_address = 'http://' + qiniu_config['bucket_dominate'] + '/' + ret['key']
        return picture_address
    except ConnectionError:
        return None

